<template>
    <div>
        <h4 style="color:deepskyblue;">深加工信息&ensp;&ensp;<el-button
                @click="deepProcessingdialogVisible = true">设置</el-button></h4>
        <br />
        <hr /><br />
        <el-descriptions column="2">
            <el-descriptions-item label="班组：">{{ form.teamOrGroup }}</el-descriptions-item>
            <el-descriptions-item label="负责人：">{{ form.personInCharge }}</el-descriptions-item>
        </el-descriptions>
        <br /> <br />
        <h4 style="color:deepskyblue;">食品安全信息</h4>
        <br />
        <hr /><br />
        <el-upload v-model:file-list="fileList" action="http://localhost:5124/api/File/UploadFile"
            list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
            :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess">
            <el-icon>
                <Plus />
            </el-icon>
        </el-upload>
        <br /> <br />
        <h4 style="color:deepskyblue;">供应商信息</h4>
        <br />
        <hr /><br />
        <h4>原料&ensp;&ensp;<el-button @click="suppliertiondialogVisible = true">设置</el-button></h4>
        <br />
        <el-descriptions column="1">
            <el-descriptions-item label="生产批次：">{{ supplierList.productionLot }}</el-descriptions-item>
        </el-descriptions>
        <br />
        <h4>相关材料</h4>
        <br />
        <hr /><br />
        <el-upload v-model:file-list="rawMaterialFileList" action="http://localhost:5124/api/File/UploadFile"
            list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="rawMaterialhandleRemove"
            :before-upload="rawMaterialbeforeAvatarUpload" :on-success="rawMaterialhandleAvatarSuccess">
            <el-icon>
                <Plus />
            </el-icon>
        </el-upload>
        <br /> <br />
        <h4>辅料&ensp;&ensp;<el-button @click="suppliertiondialogVisible = true">设置</el-button></h4>
        <br />
        <el-descriptions column="1">
            <el-descriptions-item label="生产批次：">{{ supplierList.productionLot }}</el-descriptions-item>
        </el-descriptions>
        <br />
        <h4>相关材料</h4>
        <br />
        <hr /><br />
        <el-upload v-model:file-list="AccessoriesFileList" action="http://localhost:5124/api/File/UploadFile"
            list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="AccessorieshandleRemove"
            :before-upload="AccessoriesbeforeAvatarUpload" :on-success="AccessorieshandleAvatarSuccess">
            <el-icon>
                <Plus />
            </el-icon>
        </el-upload>
        <br /> <br />
        <h4>添加剂&ensp;&ensp;<el-button @click="suppliertiondialogVisible = true">设置</el-button></h4>
        <br />
        <el-descriptions column="1">
            <el-descriptions-item label="生产批次：">{{ supplierList.productionLot }}</el-descriptions-item>
        </el-descriptions>
        <br />
        <h4>相关材料</h4>
        <br />
        <hr /><br />
        <el-upload v-model:file-list="AdditiveFileList" action="http://localhost:5124/api/File/UploadFile"
            list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="AdditivehandleRemove"
            :before-upload="AdditivebeforeAvatarUpload" :on-success="AdditivehandleAvatarSuccess">
            <el-icon>
                <Plus />
            </el-icon>
        </el-upload>
        <br /> <br />
        <h4>包材&ensp;&ensp;<el-button @click="suppliertiondialogVisible = true">设置</el-button></h4>
        <br />
        <el-descriptions column="1">
            <el-descriptions-item label="生产批次：">{{ supplierList.productionLot }}</el-descriptions-item>
        </el-descriptions>
        <br />
        <h4>相关材料</h4>
        <br />
        <hr /><br />
        <el-upload v-model:file-list="PackagingMaterialFileList" action="http://localhost:5124/api/File/UploadFile"
            list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="PackagingMaterialhandleRemove"
            :before-upload="PackagingMaterialbeforeAvatarUpload" :on-success="PackagingMaterialhandleAvatarSuccess">
            <el-icon>
                <Plus />
            </el-icon>
        </el-upload>
        <br /><br />
        <h4 style="color:deepskyblue;">企业信息&ensp;&ensp;<el-button
                @click="CorporationdialogVisible = true">设置</el-button></h4>
        <br />
        <hr /><br />
        <el-descriptions column="2">
            <el-descriptions-item label="公司名称：">{{ form1.companyName }}</el-descriptions-item>
            <el-descriptions-item label="生产许可证号：">{{ form1.productionLicense }}</el-descriptions-item>
        </el-descriptions>
        <br /> <br />
        <h4 style="color:deepskyblue;">企业照片</h4>
        <br />
        <el-upload v-model:file-list="fileList1" action="http://localhost:5124/api/File/UploadFile"
            list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove1"
            :before-upload="beforeAvatarUpload1" :on-success="handleAvatarSuccess1">
            <el-icon>
                <Plus />
            </el-icon>
        </el-upload>


        <!-- 深加工弹框 -->
        <el-dialog v-model="deepProcessingdialogVisible" title="深加工信息" width="500">
            <el-form ref="ruleFormRef" style="max-width: 600px" :model="form" :rules="rules" label-width="auto"
                class="demo-ruleForm" :size="formSize" status-icon>
                <el-form-item label="班组：" prop="teamOrGroup">
                    <el-input v-model="form.teamOrGroup" />
                </el-form-item>
                <el-form-item label="负责人：" prop="personInCharge">
                    <el-input v-model="form.personInCharge" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 公司弹框 -->
        <el-dialog v-model="CorporationdialogVisible" title="公司信息" width="500">
            <el-form ref="ruleFormRef" style="max-width: 600px" :model="form1" :rules="rules1" label-width="auto"
                class="demo-ruleForm" :size="formSize" status-icon>
                <el-form-item label="公司名称：" prop="companyName">
                    <el-input v-model="form1.companyName" />
                </el-form-item>
                <el-form-item label="生产许可证号：" prop="productionLicense">
                    <el-input v-model="form1.productionLicense" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="CorporationsubmitForm(ruleFormRef)">保存</el-button>
                </div>
            </template>
        </el-dialog>


        <!-- 供应商弹框弹框 -->
        <el-dialog v-model="suppliertiondialogVisible" width="500">
            <el-form ref="ruleFormRef" style="max-width: 600px" :model="form1" :rules="rules1" label-width="auto"
                class="demo-ruleForm" :size="formSize" status-icon>
                <el-form-item label="生产批次：">
                    <el-input v-model="supplierList.productionLot" disabled />
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, inject } from 'vue'
import { ErrorTypes, useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, collapseContextKey, type FormInstance, type FormRules } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'

import http from '@/http'

//批次号
const productionLotId = sessionStorage.getItem('productionLot')

//公司信息弹框值
const CorporationdialogVisible = ref(false)
//深加工弹框
const deepProcessingdialogVisible = ref(false)
//供应商弹框
const suppliertiondialogVisible = ref(false)

//深加工数据
const form = reactive({
    dpId: 0,
    productionLot: productionLotId,
    teamOrGroup: "",
    personInCharge: "",
    foodSafetyInformationPicture: "",
    deepProcessingCompany: ''
})

//回显深加工数据
const GetDeepProcessingInfo = () => {
    http.get('/api/DeepProcessing/GetDeepProcessingInfo?productionLot=' + productionLotId).then(res => {
        let d = res.data

        form.dpId = d.dpId
        form.deepProcessingCompany = d.deepProcessingCompany
        form.foodSafetyInformationPicture = d.foodSafetyInformationPicture
        form.personInCharge = d.personInCharge
        form.teamOrGroup = d.teamOrGroup
        getCorporationInfo()
        getPicList1()
    })
}

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
//养殖的正则验证
const rules = reactive<FormRules>({
    teamOrGroup: [
        { required: true, message: '请输入班组', trigger: 'blur' },
    ],
    personInCharge: [
        { required: true, message: '请输入负责人', trigger: 'blur' },
    ]
})

//添加深加工信息
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid) => {
        if (valid) {
            if (form.dpId == 0 || form.dpId == undefined) {
                http.post('/api/DeepProcessing/AddDeepProcessing', form).then(res => {
                    if (res.data > 0) {
                        ElMessage.success('保存成功')
                        deepProcessingdialogVisible.value = false
                        GetDeepProcessingInfo()
                    } else {
                        ElMessage.success('保存失败')
                    }
                })
            } else {
                http.put('/api/DeepProcessing/UpdateDeepProcessing', form).then(res => {
                    if (res.data > 0) {
                        ElMessage.success('保存成功')
                        deepProcessingdialogVisible.value = false
                        GetDeepProcessingInfo()
                    } else {
                        ElMessage.success('保存失败')
                    }
                })
            }
        } else {
        }
    })
}

// -------------------------------------------------------------------------------------------------------

//公司数据
const form1 = reactive({
    cId: 0,
    productionLot: productionLotId,
    companyName: "",
    companyPicture: "",
    productionLicense: ""
})

//回显公司数据
const getCorporationInfo = () => {
    http.get(`/api/DeepProcessing/GetCorporationInfo?productionLot=${productionLotId}&DeepProcessingCompanyId=${form.deepProcessingCompany}`).then(res => {
        let d = res.data
        form1.cId = d.cId
        form1.companyName = d.companyName
        form1.companyPicture = d.companyPicture
        form1.productionLicense = d.productionLicense
    })
}

//公司的正则验证
const rules1 = reactive<FormRules>({
    companyName: [
        { required: true, message: '请输入公司名称', trigger: 'blur' },
    ],
    productionLicense: [
        { required: true, message: '请输入生产许可证号', trigger: 'blur' },
    ],
})

//添加公司信息
const CorporationsubmitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid) => {
        if (valid) {
            if (form1.cId == 0 || form1.cId == undefined) {
                http.post('/api/DeepProcessing/AddCorporation', form1).then(res => {
                    if (res.data > 0) {
                        ElMessage.success('保存成功')
                        CorporationdialogVisible.value = false
                        GetDeepProcessingInfo()
                        getCorporationInfo()
                    } else {
                        ElMessage.success('保存失败')
                    }
                })
            } else {
                http.put('/api/DeepProcessing/UpdateCorporation', form1).then(res => {
                    if (res.data > 0) {
                        ElMessage.success('保存成功')
                        CorporationdialogVisible.value = false
                        GetDeepProcessingInfo()
                        getCorporationInfo()
                    } else {
                        ElMessage.success('保存失败')
                    }
                })
            }
        } else {
        }
    })
}


// -------------------------------------------------------------------------------------------------------

const supplierList = reactive({
    sId: 0,
    productionLot: productionLotId,
    rawMaterialPicture: "",
    accessoriesPicture: "",
    additivePicture: "",
    packagingMaterialPicture: ""
})

//原料图片
const rawMaterialFileList = ref<UploadUserFile[]>([])

// 原料图片判重
const rawMaterialbeforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawMaterialFileList.value.findIndex(x => x.name == rawFile.name) != -1) {
        ElMessage({
            type: 'warning',
            message: '该图片已存在！',
            duration: 2000
        });
        return false;
    }
    else {
        return true;
    }
}

//原料图片删除
const rawMaterialhandleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    rawMaterialhandUpLoad(rawMaterialFileList)
}

const rawMaterialhandUpLoad = (list: any) => {
    let str = ''
    list.value.map((x: any) => {
        str += x.name + ','
    })
    str = str.substring(0, str.length - 1)

    let info = {
        flag: 1,
        rawMaterialPicture: str,
        productionLot: productionLotId
    }

    http.post('/api/DeepProcessing/BatchSupplier', info).then()
}


//原料图片上传
const rawMaterialhandleAvatarSuccess = (data: any) => {
    rawMaterialhandUpLoad(rawMaterialFileList)
}

// -------------------------------------------------------------------------------------------------------

//辅料图片
const AccessoriesFileList = ref<UploadUserFile[]>([])

//辅料图片判重
const AccessoriesbeforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (AccessoriesFileList.value.findIndex(x => x.name == rawFile.name) != -1) {
        ElMessage({
            type: 'warning',
            message: '该图片已存在！',
            duration: 2000
        });
        return false;
    }
    else {
        return true;
    }
}

//辅料图片删除
const AccessorieshandleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    AccessorieshandUpLoad(AccessoriesFileList)
}

const AccessorieshandUpLoad = (list: any) => {
    let str = ''
    list.value.map((x: any) => {
        str += x.name + ','
    })
    str = str.substring(0, str.length - 1)

    let info = {
        flag: 2,
        accessoriesPicture: str,
        productionLot: productionLotId
    }

    http.post('/api/DeepProcessing/BatchSupplier', info).then()
}


//辅料图片上传
const AccessorieshandleAvatarSuccess = (data: any) => {
    AccessorieshandUpLoad(AccessoriesFileList)
}

// -------------------------------------------------------------------------------------------------------


//添加剂图片
const AdditiveFileList = ref<UploadUserFile[]>([])

// 添加剂图片判重
const AdditivebeforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (AdditiveFileList.value.findIndex(x => x.name == rawFile.name) != -1) {
        ElMessage({
            type: 'warning',
            message: '该图片已存在！',
            duration: 2000
        });
        return false;
    }
    else {
        return true;
    }
}

//添加剂图片删除
const AdditivehandleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    AdditivehandUpLoad(AdditiveFileList)
}

const AdditivehandUpLoad = (list: any) => {
    let str = ''
    list.value.map((x: any) => {
        str += x.name + ','
    })
    str = str.substring(0, str.length - 1)

    let info = {
        flag: 3,
        additivePicture: str,
        productionLot: productionLotId
    }

    http.post('/api/DeepProcessing/BatchSupplier', info).then()
}


//添加剂图片上传
const AdditivehandleAvatarSuccess = (data: any) => {
    AdditivehandUpLoad(AdditiveFileList)
}

// -------------------------------------------------------------------------------------------------------


//包材图片
const PackagingMaterialFileList = ref<UploadUserFile[]>([])

// 包材图片判重
const PackagingMaterialbeforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (PackagingMaterialFileList.value.findIndex(x => x.name == rawFile.name) != -1) {
        ElMessage({
            type: 'warning',
            message: '该图片已存在！',
            duration: 2000
        });
        return false;
    }
    else {
        return true;
    }
}

//原料包材删除
const PackagingMaterialhandleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    PackagingMaterialhandUpLoad(PackagingMaterialFileList)
}


const PackagingMaterialhandUpLoad = (list: any) => {
    let str = ''
    list.value.map((x: any) => {
        str += x.name + ','
    })
    str = str.substring(0, str.length - 1)

    let info = {
        flag: 4,
        packagingMaterialPicture: str,
        productionLot: productionLotId
    }

    http.post('/api/DeepProcessing/BatchSupplier', info).then()
}


//包材图片上传
const PackagingMaterialhandleAvatarSuccess = (data: any) => {
    PackagingMaterialhandUpLoad(PackagingMaterialFileList)
}

// -------------------------------------------------------------------------------------------------------


const GetSupplierPicture = () => {
    http.get(`/api/DeepProcessing/GetSupplierPicture?productionLot=${productionLotId}`).then(res => {
        rawMaterialFileList.value = res.data[0].dtos
        AccessoriesFileList.value = res.data[1].dtos
        AdditiveFileList.value = res.data[2].dtos
        PackagingMaterialFileList.value = res.data[3].dtos
    })
}


// -------------------------------------------------------------------------------------------------------------------------------------
//食品安全图片
const fileList = ref<UploadUserFile[]>([])

// 食品安全图片判重
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (fileList.value.findIndex(x => x.name == rawFile.name) != -1) {
        ElMessage({
            type: 'warning',
            message: '该图片已存在！',
            duration: 2000
        });
        return false;
    }
    else {
        return true;
    }
}

//查看大图片
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}

//深加工图片删除
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    handUpLoad(fileList)
}

//显示食品安全图片
const getPicList = () => {
    http.get('/api/DeepProcessing/GetDeepProcessingPicture?productionLot=' + productionLotId).then(res => {
        if (res.data == null) return
        fileList.value = res.data
    })
}


const handUpLoad = (list: any) => {
    let str = ''
    list.value.map((x: any) => {
        str += x.name + ','
    })
    str = str.substring(0, str.length - 1)

    let info = {
        productionLot: productionLotId,
        urlImg: str
    }

    http.post('/api/DeepProcessing/BatchDeepProcessingPicList', info).then(res => {
        if (res.data > 0) {
            GetDeepProcessingInfo()
        }
    })
}


//深加工图片上传
const handleAvatarSuccess = (data: any) => {
    handUpLoad(fileList)
}

// -------------------------------------------------------------------------------------------------------

//企业图片
const fileList1 = ref<UploadUserFile[]>([])

// 企业图片判重
const beforeAvatarUpload1: UploadProps['beforeUpload'] = (rawFile) => {
    if (fileList1.value.findIndex(x => x.name == rawFile.name) != -1) {
        ElMessage({
            type: 'warning',
            message: '该图片已存在！',
            duration: 2000
        });
        return false;
    }
    else {
        return true;
    }
}

//删除企业照片
const handleRemove1: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    handUpLoad1(fileList1)
}

//显示公司图片
const getPicList1 = () => {
    http.get(`/api/DeepProcessing/GetCorporationPicture?productionLot=${productionLotId}&DeepProcessingCompanyId=${form.deepProcessingCompany}`).then(res => {
        if (res.data == null) return
        fileList1.value = res.data
    })
}

const handUpLoad1 = (list: any) => {
    let str = ''
    list.value.map((x: any) => {
        str += x.name + ','
    })
    str = str.substring(0, str.length - 1)

    let info = {
        productionLot: productionLotId,
        urlImg: str,
        dpId: form.deepProcessingCompany
    }

    http.post('/api/DeepProcessing/BatchCorporationPicList', info).then(res => {
        if (res.data > 0) {
            GetDeepProcessingInfo()
        }
    })
}

//添加企业照片
const handleAvatarSuccess1 = (data: any) => {
    handUpLoad1(fileList1)
}

// -------------------------------------------------------------------------------------------------------

onMounted(() => {
    GetDeepProcessingInfo()
    getPicList()
    GetSupplierPicture()
})

</script>

<style scoped></style>